<template>
  <div class="cart-edit">
    <h2>修改购物车数量</h2>
    
    <el-form :model="form" label-width="120px">
      <el-form-item label="图书名称">
        <el-input v-model="bookName" disabled />
      </el-form-item>
      <el-form-item label="单价">
        <el-input v-model="price" disabled />
      </el-form-item>
      <el-form-item label="数量">
        <el-input-number v-model="form.quantity" :min="1" :max="100" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'

interface CartItem {
  bookId: number
  bookName: string
  quantity: number
  price: number
}

interface CartVo {
  cartId: number
  cartItemList?: CartItem[]
}

const route = useRoute()
const router = useRouter()

const form = ref({
  cartId: Number(route.params.cartId),
  bookId: Number(route.params.bookId),
  quantity: 1,
})

// 添加图书信息
const bookName = ref('')
const price = ref(0)

// 获取当前购物车项信息
// 获取当前购物车项信息
const fetchCartItem = async () => {
  try {
    const { data } = await request.get<CartVo[]>('/user/cart/list')
    
    // 查找匹配的购物车项
    const cartItem = data
      .flatMap(cart => 
        (cart.cartItemList || []).map(item => ({
          ...item,
          cartId: cart.cartId // 将cartId附加到每个item上
        }))
      )
      .find(item => 
        item.bookId === form.value.bookId && 
        item.cartId === form.value.cartId
      )
    
    if (cartItem) {
      form.value.quantity = cartItem.quantity
      bookName.value = cartItem.bookName
      price.value = cartItem.price
    }
  } catch (error) {
    ElMessage.error('获取购物车信息失败')
  }
}
// 提交修改
const handleSubmit = async () => {
  try {
    await request.put('/user/cart/update', {
      cartId: form.value.cartId,
      bookId: form.value.bookId,
      quantity: form.value.quantity
    })
    ElMessage.success('修改成功')
    router.push({ name: 'CartList' })
  } catch (error) {
    ElMessage.error('修改失败')
    console.error(error)
  }
}

// 取消修改
const handleCancel = () => {
  router.go(-1)
}

onMounted(() => {
  fetchCartItem()
})
</script>

<style scoped>
.cart-edit {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}
</style>